<?php
/**
 * 营销活动管理
 *
 * @author maolvxiansheng 2018-09-06 21:10
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */

use Shopnc\Tpl;

defined('InShopNC') or exit('Access Invalid!');


class marketing_activityControl extends SystemControl
{
    public function __construct()
    {
        parent::__construct();
        Language::read('marketing_activity');
   
        $model_marketing               = Model('marketing_activity');
        $this->model_marketing         = $model_marketing;
        $this->marketing_activity_type = $model_marketing->getMarketingActivityType();
    }

    /**
     * 活动列表
     */
  
    public function indexOp()
    {
        $this->marketing_activityOp();
    }

    /**
     * 活动列表/删除活动
     */
    public function marketing_activityOp()
    {
        Tpl::showpage('marketing_activity.index');
    }

    /**
     * 活动列表/删除活动XML
     */
    public function marketing_activity_xmlOp()
    {
        $condition = array();

        if ($_REQUEST['advanced']) {
            
            if (strlen($q = trim((string)$_REQUEST['marketing_activity_title']))) {
                $condition['marketing_activity_title'] = $q;
            }
            
            if (strlen($q = trim((string)$_REQUEST['marketing_activity_state']))) {
                $condition['marketing_activity_state'] = (int)$q;
            }
            
            if (strlen($q = trim((string)$_REQUEST['marketing_activity_type']))) {
                $condition['marketing_activity_type'] = (int)$q;
            }

            $pdates = array();
            
            if (strlen($q = trim((string)$_REQUEST['pdate1'])) && ($q = strtotime($q . ' 00:00:00'))) {
                $pdates[] = "marketing_activity.marketing_activity_end_date >= {$q}";
            }
            
            if (strlen($q = trim((string)$_REQUEST['pdate2'])) && ($q = strtotime($q . ' 00:00:00'))) {
                $pdates[] = "marketing_activity.marketing_activity_start_date <= {$q}";
            }
            if ($pdates) {
                $condition['pdates'] = implode(' or ', $pdates);
            }

        } else {
            if (strlen($q = trim($_REQUEST['query'])) > 0) {
                switch ($_REQUEST['qtype']) {
                    case 'marketing_activity_title':
                        $condition['marketing_activity_title'] = $q;
                        break;
                }
            }
        }

        switch ($_REQUEST['sortname']) {
            case 'marketing_activity_sort':
            case 'marketing_activity_start_date':
            case 'marketing_activity_end_date':
                $sort = $_REQUEST['sortname'];
                break;
            default:
                $sort = 'marketing_activity_id';
                break;
        }
        if ($_REQUEST['sortorder'] != 'asc') {
            $sort .= ' desc';
        }

        // 只显示商品活动
        $condition['order'] = $sort;

        $marketing_activity = Model('marketing_activity');
       
        $field              = 'marketing_activity.marketing_activity_id,marketing_activity.marketing_activity_title,marketing_activity.marketing_activity_type,marketing_activity.marketing_activity_banner,marketing_activity.marketing_activity_apply_start_date,marketing_activity.marketing_activity_apply_end_date,marketing_activity.marketing_activity_start_date,marketing_activity.marketing_activity_end_date,marketing_activity.store_goods_limit,marketing_activity.marketing_activity_sort,marketing_activity.marketing_activity_state,marketing_activity.marketing_activity_show,marketing_activity_extend.marketing_activity_desc';
        $list               = $marketing_activity->getList($condition, $field, 0, $_REQUEST['rp']);

        
        $data              = array();
        $data['now_page']  = $marketing_activity->shownowpage();
        $data['total_num'] = $marketing_activity->gettotalnum();

        foreach ($list as $val) {
            $o = '';
            //列表操作按钮 - start
            
            if ($val['marketing_activity_end_date'] < TIMESTAMP) {
                $o .= '<a class="btn red confirm-del-on-click" href="javascript:;" data-href="index.php?act=marketing_activity&op=del&marketing_activity_id=' .
                    $val['marketing_activity_id'] .
                    '"><i class="fa fa-trash-o"></i>删除</a>';
            }

            $if_show = (isset($val['marketing_activity_show']) && ($val['marketing_activity_show'] == 0)) ? '显示' : '隐藏';
           
            $o       .= '<a class="btn red" href="javascript:;" data-href="index.php?act=marketing_activity&op=alter_show_state&marketing_activity_id=' .
                $val['marketing_activity_id'] . '">' . $if_show . '</a>';

            $o .= '<span class="btn"><em><i class="fa fa-cog"></i>设置<i class="arrow"></i></em><ul>';

            $o .= '<li><a href="index.php?act=marketing_activity&op=edit&marketing_activity_id=' .
          
                $val['marketing_activity_id'] .
               
                '">编辑活动</a></li>';

            
            switch ($val['marketing_activity_type'])
            {

                case 3:
                    $o .= '<li><a href="index.php?act=promotion_kanjia&op=kanjia_detail&marketing_activity_id=' .
                        $val['marketing_activity_id'] .
                        '">处理申请</a></li>';
                    break;
                case 4:
                    $o .= '<li><a href="index.php?act=promotion_pintuan&op=pintuan_detail&marketing_activity_id=' .
                        $val['marketing_activity_id'] .
                        '">处理申请</a></li>';
                    break;
                default:
                    $o .= '<li><a href="index.php?act=marketing_activity&op=detail&marketing_activity_id=' .
                        $val['marketing_activity_id'] .
                        '">处理申请</a></li>';
            }

            if ($val['marketing_activity_state'] == 1 && $val['marketing_activity_end_date'] > TIMESTAMP) {
                $o .= '<li><a href="index.php?act=marketing_activity&op=activity_apply&marketing_activity_id=' .
                    $val['marketing_activity_id'] .
                    '">活动报名</a></li>';
            }

            $o .= '</ul></span>';
            //列表操作按钮 - end

            
            $i                             = array();
            $i['operation']                = $o;
            $i['marketing_activity_id']    = $val['marketing_activity_id'];
            $i['marketing_activity_sort']  = '<span class="editable" title="可编辑" style="width:50px;" data-live-inline-edit="marketing_activity_sort">' .
                $val['marketing_activity_sort'] . '</span>';
            $i['marketing_activity_title'] = '<textarea style="position: absolute;top: 0;left: 0;opacity: 0;z-index: -10;" >copy_link</textarea><span onclick="clickCopy(this)" title="点击复制" style="width:333px;" copy_link="' . $val['store_activity_apply'] . '">' .
                $val['marketing_activity_title'] . '</span>';

            $i['marketing_activity_type_text']  = $val['marketing_activity_type_text'];
            $i['marketing_activity_desc']       = $val['marketing_activity_desc'];
            $i['marketing_activity_apply_date'] = $val['marketing_activity_apply_date'];
            $i['marketing_activity_date']       = $val['marketing_activity_date'];
           
            $i['marketing_activity_state_text'] = $val['marketing_activity_state_text'];
			$i['marketing_activity_type']   = $val['marketing_activity_type'];
            $data['list'][$val['marketing_activity_id']] = $i;
        }

        echo Tpl::flexigridXML($data);
        exit;
    }

    /**
     * 新建活动/保存新建活动
     */

    public function newOp()
    {
        //新建处理
        if ($_POST['form_submit'] != 'ok') {
            Tpl::output('marketing_activity_type', $this->marketing_activity_type);
            Tpl::showpage('marketing_activity.add');
            exit;
        }
        //提交表单
        $obj_validate                = new Validate();
        $obj_validate->validateparam = array(
            array("input" => $_POST["marketing_activity_title"], "require" => "true", "message" => Language::get('activity_new_title_null')),
            array("input" => $_POST["marketing_activity_apply_start_date"], "require" => "true", "message" => Language::get('activity_new_applystartdate_null')),
            array("input" => $_POST["marketing_activity_apply_end_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_apply_start_date']}", "message" => Language::get('activity_new_applyenddate_size')),
            array('input' => $_POST['store_goods_limit'], 'require' => 'true', 'validator' => 'Range', 'min' => 0, 'max' => 255, 'message' => Language::get('activity_new_storegoodslimit_maxerror')),
            array("input" => $_POST["marketing_activity_start_date"], "require" => "true", "message" => Language::get('activity_new_startdate_null')),
            array("input" => $_POST["marketing_activity_end_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_start_date']}", "message" => Language::get('activity_new_enddate_null')),
            array("input" => $_POST["marketing_activity_start_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_apply_start_date']}", "message" => Language::get('activity_new_applyStart_activityStart_size')),  //检查报名开始时间是否大于等于活动开始时间
            array("input" => $_POST["marketing_activity_end_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_apply_end_date']}", "message" => Language::get('activity_new_applyEnd_activityEnd_size')),  //检查报名结束时间是否大于等于活动结束时间
            array("input" => $_POST["marketing_activity_style"], "require" => "true", "message" => Language::get('activity_new_style_null')),
            array('input' => $_POST['marketing_activity_type'], 'require' => 'true', "validator" => "custom", "regexp" => "/^(1|2|3|4)$/", 'message' => Language::get('activity_new_type_error')),
            array('input' => $_FILES['marketing_activity_banner']['name'], 'require' => 'true', 'message' => Language::get('activity_new_banner_null')),
            array('input' => $_POST['marketing_activity_sort'], 'require' => 'true', 'validator' => 'Range', 'min' => 0, 'max' => 255, 'message' => Language::get('activity_new_sort_error')),
        );
        $error                       = $obj_validate->validate();
        if ($error != '') {
            showMessage(Language::get('error') . $error, '', '', 'error');
        }
        if ($_POST['marketing_activity_type'] == 3 || $_POST['marketing_activity_type']== 4)
        {
            if($_POST['min_num'] < 2){
                showMessage('参团人数不能少于两人' . $error, '', '', 'error');
            }
        }
        //上传图片
        $upload = new UploadFile();
        $upload->set('default_dir', ATTACH_ACTIVITY);
        $result = $upload->upfile('marketing_activity_banner');
        if (!$result) {
            showMessage($upload->error);
        }
        /*事务开始*/
        //保存营销活动
        $model_marketing = $this->model_marketing;
        //添加数据
        try {
            $model_marketing->beginTransaction();
            $input                                        = array();
            $input['marketing_activity_title']            = trim($_POST['marketing_activity_title']);
            $input['marketing_activity_type']             = (int)$_POST['marketing_activity_type'];
            $input['marketing_activity_banner']           = $upload->file_name;
            $input['marketing_activity_style']            = trim($_POST['marketing_activity_style']);
            $input['marketing_activity_desc']             = trim($_POST['marketing_activity_desc']);
            $input['marketing_activity_sort']             = intval(trim($_POST['marketing_activity_sort']));
            $input['marketing_activity_apply_start_date'] = strtotime(trim($_POST['marketing_activity_apply_start_date']));
            $input['marketing_activity_apply_end_date']   = strtotime(trim($_POST['marketing_activity_apply_end_date']));
            $input['marketing_activity_start_date']       = strtotime(trim($_POST['marketing_activity_start_date']));
            $input['marketing_activity_end_date']         = strtotime(trim($_POST['marketing_activity_end_date']));
            $input['store_goods_limit']                   = (int)$_POST['store_goods_limit'];
            $input['marketing_activity_state']            = intval($_POST['marketing_activity_state']);
            $input['marketing_activity_show']             = intval($_POST['marketing_activity_show']);
            $input['create_time']                         = TIMESTAMP;
            $input['min_num']                             = intval($_POST['min_num']);
            $result = $model_marketing->add($input);
            /*砍价*/
            if ($input['marketing_activity_type'] == 3 && $result)
            {
                $model_kanjia                   = Model('p_kanjia');
                $param                          = array();
                $param['kanjia_name']           = trim($_POST['marketing_activity_title']);
                $param['quota_id']              = 0;
                $param['start_time']            = strtotime(trim($_POST['marketing_activity_start_date']));
                $param['end_time']              = strtotime(trim($_POST['marketing_activity_end_date']));
                $param['store_id']              = 0;
                $param['store_name']            = 0;
                $param['member_id']             = 0;
                $param['member_name']           = 0;
                $param['min_num']               = intval($_POST['min_num']);
                $param['marketing_activity_id'] = $result;
                $result_gl = $model_kanjia->add($param);
                /*拼团*/
            }
            elseif ($input['marketing_activity_type'] == 4 && $result) {
                $model_pintuan                  = Model('p_pintuan');
                $param                          = array();
                $param['pintuan_name']          = trim($_POST['marketing_activity_title']);
                $param['quota_id']              = 0;
                $param['start_time']            = strtotime(trim($_POST['marketing_activity_start_date']));
                $param['end_time']              = strtotime(trim($_POST['marketing_activity_end_date']));
                $param['store_id']              = 0;
                $param['store_name']            = 0;
                $param['member_id']             = 0;
                $param['member_name']           = 0;
                $param['min_num']               = intval($_POST['min_num']);
                $param['marketing_activity_id'] = $result;
                $result_gl = $model_pintuan->add($param);
            }
            if($result_gl && $result)
            {
                $model_marketing->commit();
            }
            else{
                throw new Exception($model_marketing->getErrorInfo());
            }
        } catch (Exception $e) {
            //回滚事务
            $model_marketing->rollback();
            //添加失败则删除刚刚上传的图片,节省空间资源
            @unlink(BASE_UPLOAD_PATH . DS . ATTACH_ACTIVITY . DS . $upload->file_name);
            // showMessage(Language::get('nc_common_op_fail'));
            showMessage($model_marketing->getErrorInfo());
        }
        $this->log(L('nc_add,activity_index') . '[' . $_POST['marketing_activity_title'] . ']', null);
        showMessage(Language::get('nc_common_op_succ'), 'index.php?act=marketing_activity&op=marketing_activity');

    }

    /**
     * 异步修改
     */
    
    public function ajaxOp()
    {
        if (in_array($_GET['branch'], array('marketing_activity_title', 'marketing_activity_sort'))) {
            $marketing_activity = Model('marketing_activity');
           
            $update_array       = array();
            switch ($_GET['branch']) {
                /**
                 * 活动主题
                 */
                case 'marketing_activity_title':
                    
                    if (trim($_GET['value']) == '') exit;
                    break;
                /**
                 * 排序
                 */
                case 'marketing_activity_sort':
                    
                    if (preg_match('/^\d+$/', trim($_GET['value'])) <= 0 or intval(trim($_GET['value'])) < 0 or intval(trim($_GET['value'])) > 255) exit;
                    break;
                default:
                
                    exit;
            }
            $update_array[$_GET['column']] = trim($_GET['value']);
            
            if ($marketing_activity->updates($update_array, intval($_GET['id'])))
                echo 'true';
        } elseif (in_array($_GET['branch'], array('marketing_activity_detail_sort'))) {
            switch ($_GET['branch']) {
                /**
                 * 排序
                 */
                case 'marketing_activity_detail_sort':
                
                    if (preg_match('/^\d+$/', trim($_GET['value'])) <= 0 or intval(trim($_GET['value'])) < 0 or intval(trim($_GET['value'])) > 255) exit;
                    break;
                default:
                
                    exit;
            }
            $marketing_activity_id = isset($_GET['marketing_activity_id']) ? (int)$_GET['marketing_activity_id'] : 0;
           
            if (!$marketing_activity_id) return 'false';
            $marketing_activity            = Model('marketing_activity');
            $update_array[$_GET['column']] = trim($_GET['value']); //修改数据
           
            if ($marketing_activity->updatesGoodsData($marketing_activity_id, (int)$_GET['id'], $update_array))
                echo 'true';
        }
    }

    /**
     * 删除活动
     */
    public function delOp()
    {
        $marketing_activityIds = array();
       
        foreach (explode(',', (string)$_REQUEST['marketing_activity_id']) as $i) {
            $marketing_activityIds[(int)$i] = null;
        }
        unset($marketing_activityIds[0]);
        $marketing_activityIds = array_keys($marketing_activityIds);

        if (empty($marketing_activityIds)) {
            $this->jsonOutput(Language::get('activity_del_choose_activity'));
        }

      
        try {
            // 删除数据先删除横幅图片，节省空间资源
            foreach ($marketing_activityIds as $v) {
                $this->delActivityBanner($v);
            }
        } catch (Exception $e) {
            $this->jsonOutput($e->getMessage());
        }

       
        //只有关闭且过期的活动，能删除
       
        $marketing_activity = Model('marketing_activity');

        $del_staet          = $marketing_activity->delMarketingActivity($marketing_activityIds);
        if (!$del_staet) {
            $this->jsonOutput($marketing_activity->getErrorInfo());
        }
        
        /*删除砍价/拼团数据*/
        for ($i=0;count($marketing_activityIds) > $i ;$i++){
            $marketing_data = $marketing_activity->getOneById($marketing_activityIds[$i]);
            switch ($marketing_data['marketing_activity_type'])
            {
                case 3:
                    Model('p_kanjia')->del(array('marketing_activity_id'=>$marketing_activityIds[$i]));
                    $this->log('删除砍价活动' . '[ID:' . $marketing_activityIds[$i] . ']', null);
                    break;
                case 4:
                    Model('p_pintuan')->del(array('marketing_activity_id'=>$marketing_activityIds[$i]));
                    $this->log('删除拼团活动' . '[ID:' . $marketing_activityIds[$i] . ']', null);
                    break;
            }
        }
        $this->log(L('nc_del,activity_index') . '[ID:' . implode(',', $marketing_activityIds) . ']', null);
        $this->jsonOutput();

    }

    /**
     * ajax 修改活动显示状态
     * @return json
     */
    public function alter_show_stateOp()
    {
        $marketing_activity_id = isset($_GET['marketing_activity_id']) ? (int)$_GET['marketing_activity_id'] : 0;
        if (!$marketing_activity_id) $this->jsonOutput('请选择操作对象');

       
        $marketing_activity = Model('marketing_activity');
        //是否存在该数据
     
        $map           = array(
            'marketing_activity_id' => $marketing_activity_id
        );
        $activity_data = $marketing_activity->table('marketing_activity')->field('marketing_activity_id,marketing_activity_show')->where($map)->find();
        if (empty($activity_data)) $this->jsonOutput('不存在该数据');

        //修改数据
        $alter_data['marketing_activity_show'] = (isset($activity_data['marketing_activity_show']) && ($activity_data['marketing_activity_show'] == 1)) ? 0 : 1;
       
        $result                                = $marketing_activity->updates($alter_data, $marketing_activity_id);

       
        if ($result) $this->jsonOutput();

        $this->jsonOutput('操作失败');
    }

    /**
     * 编辑活动/保存编辑活动
     */
    public function editOp()
    {
       
        $marketing_activity = Model('marketing_activity');

        if ($_POST['form_submit'] != 'ok') {
            $marketing_activity_id = isset($_GET['marketing_activity_id']) ? (int)$_GET['marketing_activity_id'] : 0;
            if (empty($marketing_activity_id)) {
                showMessage(Language::get('miss_argument'));
            }
            //获取活动详情
           
            $row = $marketing_activity->getOneById($marketing_activity_id);
            //判断活动是否可以修改
            $if_alter = $marketing_activity->chechIfAllowAlter($marketing_activity_id);
           
            Tpl::output('if_alter', $if_alter);
            Tpl::output('marketing_activity', $row);
            Tpl::output('marketing_activity_type', $this->marketing_activity_type);
            Tpl::showpage('marketing_activity.edit');
            exit;
        }

        //提交表单
        $marketing_activity_id = isset($_POST['marketing_activity_id']) ? (int)$_POST['marketing_activity_id'] : 0;
        if (empty($marketing_activity_id)) {
            showMessage(Language::get('miss_argument'));
        }
        //判断拼团砍价人数
        if ($_POST['marketing_activity_type'] == 3 || $_POST['marketing_activity_type']== 4)
        {
            if($_POST['min_num'] < 2){
                showMessage('参团人数不能少于两人' );
            }
        }

        $if_alter     = $marketing_activity->chechIfAllowAlter($marketing_activity_id);
        $obj_validate = new Validate();  //校验器
        if ($if_alter) { //允许修改
            $obj_validate->validateparam = array(
                array("input" => $_POST["marketing_activity_title"], "require" => "true", "message" => Language::get('activity_new_title_null')),
                array("input" => $_POST["marketing_activity_apply_start_date"], "require" => "true", "message" => Language::get('activity_new_applystartdate_null')),
                array("input" => $_POST["marketing_activity_apply_end_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_apply_start_date']}", "message" => Language::get('activity_new_applyenddate_size')),
                array('input' => $_POST['store_goods_limit'], 'require' => 'true', 'validator' => 'Range', 'min' => 0, 'max' => 255, 'message' => Language::get('activity_new_storegoodslimit_maxerror')),
                array("input" => $_POST["marketing_activity_start_date"], "require" => "true", "message" => Language::get('activity_new_startdate_null')),
                array("input" => $_POST["marketing_activity_end_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_start_date']}", "message" => Language::get('activity_new_enddate_null')),
                array("input" => $_POST["marketing_activity_start_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_apply_start_date']}", "message" => Language::get('activity_new_applyStart_activityStart_size')),  //检查报名开始时间是否小于活动开始时间
                array("input" => $_POST["marketing_activity_end_date"], "require" => "true", 'validator' => 'Compare', 'operator' => '>', 'to' => "{$_POST['marketing_activity_apply_end_date']}", "message" => Language::get('activity_new_applyEnd_activityEnd_size')),  //检查报名结束时间是否小于活动结束时间
                array("input" => $_POST["marketing_activity_style"], "require" => "true", "message" => Language::get('activity_new_style_null')),
                array('input' => $_POST['marketing_activity_type'], 'require' => 'true', "validator" => "custom", "regexp" => "/^(1|2|3|4)$/", 'message' => Language::get('activity_new_type_error')),
                array('input' => $_POST['marketing_activity_sort'], 'require' => 'true', 'validator' => 'Range', 'min' => 0, 'max' => 255, 'message' => Language::get('activity_new_sort_error'))
            );
        } else {
            $obj_validate->validateparam = array(
              
                array("input" => $_POST["marketing_activity_title"], "require" => "true", "message" => Language::get('activity_new_title_null')),
                array('input' => $_POST['marketing_activity_sort'], 'require' => 'true', 'validator' => 'Range', 'min' => 0, 'max' => 255, 'message' => Language::get('activity_new_sort_error'))
            );
        }

        $error = $obj_validate->validate();
       
        if ($error != '') {
            showMessage(Language::get('error') . $error, '', '', 'error');
        }
        //构造更新内容
        $input = array();
        // 如果有上传图片
        if ($_FILES['marketing_activity_banner']['name'] != '') {
            $upload = new UploadFile();
            $upload->set('default_dir', ATTACH_ACTIVITY);
            $result = $upload->upfile('marketing_activity_banner');
            if (!$result) {
                showMessage($upload->error);
            }
            $input['marketing_activity_banner'] = $upload->file_name;
        }
        if ($if_alter) {  //允许修改
            $input['marketing_activity_type']             = (int)$_POST['marketing_activity_type'];
            $input['marketing_activity_style']            = trim($_POST['marketing_activity_style']);
            $input['marketing_activity_apply_start_date'] = strtotime(trim($_POST['marketing_activity_apply_start_date']));
            $input['marketing_activity_apply_end_date']   = strtotime(trim($_POST['marketing_activity_apply_end_date']));
            $input['marketing_activity_start_date']       = strtotime(trim($_POST['marketing_activity_start_date']));
            $input['marketing_activity_end_date']         = strtotime(trim($_POST['marketing_activity_end_date']));
            $input['store_goods_limit']                   = (int)$_POST['store_goods_limit'];

        }
        $input['marketing_activity_title'] = trim($_POST['marketing_activity_title']);
        $input['marketing_activity_desc']  = trim($_POST['marketing_activity_desc']);

        $input['marketing_activity_sort']  = intval(trim($_POST['marketing_activity_sort']));
        $input['marketing_activity_state'] = intval($_POST['marketing_activity_state']);
        $input['marketing_activity_show']  = intval($_POST['marketing_activity_show']);
        $input['min_num']                  = intval($_POST['min_num']);

        //如果有重新上传图片，获取之前的图片地址
        if (isset($input['marketing_activity_banner']) && !empty($input['marketing_activity_banner'])) {
            $map                       = array('marketing_activity_id' => $marketing_activity_id);
            $activity_data             = $marketing_activity->table('marketing_activity')->field('marketing_activity_id,marketing_activity_banner')->where($map)->find();
            $marketing_activity_banner = isset($activity_data['marketing_activity_banner']) ? $activity_data['marketing_activity_banner'] : '';
        }
        $marketing_activity_datas = Model('marketing_activity')->getOneData(array('marketing_activity.marketing_activity_id' => $marketing_activity_id));
        /*如果活动类型改动 除砍价p_kanjia与拼团p_pintuan记录*/
        if(intval($marketing_activity_datas['marketing_activity_type']) == 1 ||  intval($marketing_activity_datas['marketing_activity_type']) == 2){
            $p_pintuan_info = Model('p_pintuan') ->getInfo(array('marketing_activity_id' => $marketing_activity_id));
            if(isset($p_pintuan_info)){
                Model('p_pintuan') ->del(array('marketing_activity_id' => $marketing_activity_id));
            }
            $p_kanjia_info = Model('p_kanjia') ->getInfo(array('marketing_activity_id' => $marketing_activity_id));
            if(isset($p_kanjia_info)){
                Model('p_kanjia') ->del(array('marketing_activity_id' => $marketing_activity_id));
            }
        }

        if(intval($marketing_activity_datas['marketing_activity_type']) == 3 ){
            $model_kanjia                   = Model('p_kanjia');
            $p_kanjia_info = $model_kanjia ->getInfo(array('marketing_activity_id' => $marketing_activity_id));
            $param                          = array();
            if(!empty($p_kanjia_info)){
                $param['kanjia_name']           = trim($input['marketing_activity_title']);
                if ($if_alter) {  //允许修改
                    $param['start_time']            = strtotime(trim($_POST['marketing_activity_start_date']));
                    $param['end_time']              = strtotime(trim($_POST['marketing_activity_end_date']));
                    $param['min_num']               = intval($_POST['min_num']);
                }
                $model_kanjia->edit($param, array('marketing_activity_id' => $marketing_activity_id));
            }else{
                $param['kanjia_name']           = trim($input['marketing_activity_title']);
                $param['quota_id']              = 0;
                $param['start_time']            = strtotime(trim($_POST['marketing_activity_start_date']));
                $param['end_time']              = strtotime(trim($_POST['marketing_activity_end_date']));
                $param['store_id']              = 0;
                $param['store_name']            = 0;
                $param['member_id']             = 0;
                $param['member_name']           = 0;
                $param['min_num']               = intval($_POST['min_num']);
                $param['marketing_activity_id'] = $marketing_activity_id;
                $model_kanjia->add($param);
            }
        }elseif(intval($marketing_activity_datas['marketing_activity_type']) == 4){
            $model_pintuan                  = Model('p_pintuan');
            $p_pintuan_info = $model_pintuan ->getInfo(array('marketing_activity_id' => $marketing_activity_id));
            $param                          = array();
            if(!empty($p_pintuan_info)){
                $param['pintuan_name']          = trim($_POST['marketing_activity_title']);
                if ($if_alter) {  //允许修改
                    $param['start_time']    = strtotime(trim($_POST['marketing_activity_start_date']));
                    $param['end_time']      = strtotime(trim($_POST['marketing_activity_end_date']));
                    $param['min_num']       = intval($_POST['min_num']);
                }
                $model_pintuan->edit($param, array('marketing_activity_id' => $marketing_activity_id));
            }else{
                $param['pintuan_name']          = trim($input['marketing_activity_title']);
                $param['quota_id']              = 0;
                $param['start_time']            = strtotime(trim($_POST['marketing_activity_start_date']));
                $param['end_time']              = strtotime(trim($_POST['marketing_activity_end_date']));
                $param['store_id']              = 0;
                $param['store_name']            = 0;
                $param['member_id']             = 0;
                $param['member_name']           = 0;
                $param['min_num']               = intval($_POST['min_num']);
                $param['marketing_activity_id'] = $marketing_activity_id;
                $model_pintuan->add($param);
            }
        }

        $result = $marketing_activity->updates($input, $marketing_activity_id, $if_alter);
       
        if ($result) {
            if (empty($marketing_activity_banner)) {
           
                @unlink(BASE_UPLOAD_PATH . DS . ATTACH_ACTIVITY . DS . $marketing_activity_banner);
            }
         
            $this->log(L('nc_edit,activity_index') . '[ID:' . $marketing_activity_id . ']', null);
            showMessage(Language::get('nc_common_save_succ'), 'index.php?act=marketing_activity&op=marketing_activity');
        } else {
            if (isset($input['marketing_activity_banner']) && !empty($input['marketing_activity_banner'])) {
        
                @unlink(BASE_UPLOAD_PATH . DS . ATTACH_ACTIVITY . DS . $input['marketing_activity_banner']);
            }
            // showMessage(Language::get('nc_common_save_fail'));
            showMessage($marketing_activity->getErrorInfo());
        }
    }

    /**
     * 活动细节列表
     */
    public function detailOp()
    {
        $states = Model('p_newbie_goods')->getMansongStateArray();
        Tpl::output('states', $states);

     
        $marketing_activity      = Model('marketing_activity');
        $marketing_activity_data = $marketing_activity->getOneById($_REQUEST['marketing_activity_id']);
        if (empty($marketing_activity_data)) {
            showMessage('不存在该数据');
        }
        //获取所有未结束且状态为开启的活动
      
        $map           = array(
            'marketing_activity_end_date' => array('gt', TIMESTAMP),
        
            'marketing_activity_state'    => 1
        );
        $activity_list = $marketing_activity->table('marketing_activity')->field('marketing_activity_id,marketing_activity_title,marketing_activity_type')->where($map)->select();

        $activity_list_html = '';
        
        foreach ($activity_list as $item) {
            $activity_list_html .= '<li><input name="marketing_activity_state" value="' . $item['marketing_activity_id'] . '" type="radio">' . $item['marketing_activity_title'] . '</li>';
        }
        Tpl::output('activity_list_html', $activity_list_html);

        //确定操作对象
        $model_name = $marketing_activity->activityTypeShiftModel($marketing_activity_data['marketing_activity_type']);
        if (!$model_name) {
            return array();  //营销类型错误
        }
        $model_name = Model($model_name);


        Tpl::output('marketing_activity_detail', $marketing_activity_data);
        Tpl::output('model_name', $model_name);
        Tpl::showpage('marketing_activity_detail.index');
    }

    /**
     * 活动细节列表XML
     */
    public function detail_xmlOp()
    {
        $marketing_activity_id = isset($_GET['marketing_activity_id']) ? (int)$_GET['marketing_activity_id'] : 0;

      
        $condition                          = array();
        $condition['marketing_activity_id'] = $marketing_activity_id;

        if ($_REQUEST['advanced']) { //高级搜索
           
            if (strlen($q = trim((string)$_REQUEST['store_name']))) {  //店铺名称
                $condition['store_name'] = $q;
            }
          
            if (strlen($q = trim((string)$_REQUEST['goods_name']))) {   //商品名称
                $condition['goods_name'] = $q;
            }
           
            if (strlen($q = trim((string)$_REQUEST['marketing_activity_detail_state']))) {
                $condition['marketing_activity_detail_state'] = (int)$q;
            }
        } else {
            if (strlen($q = trim($_REQUEST['query'])) > 0) {
                switch ($_REQUEST['qtype']) {
                    case 'store_name':
                        $condition['store_name'] = $q;
                        break;
                    case 'goods_name':
                        $condition['goods_name'] = $q;
                        break;
                }
            }
        }
        $condition['order'] = 'create_time desc';

        $marketing_activity = Model('marketing_activity');
       
        $list               = $marketing_activity->getGoodsList($condition, 0, $_REQUEST['rp']);

     
        $data              = array();
        $data['now_page']  = $marketing_activity->shownowpage();
        $data['total_num'] = $marketing_activity->gettotalnum();
        foreach ($list as $val) {
            //列表操作按钮 - end
            $i['operation']                                     = $val['operation'];
            $i['activity_goods_sort']                           = '<span class="editable" title="可编辑" style="width:50px;" data-live-inline-edit="activity_goods_sort">' . $val['activity_goods_sort'] . '</span>';
            $i['goods_name']                                    = $val['goods_name'];
            $i['goods_state_text']                              = $val['goods_state_text'];
            $i['store_name']                                    = '<a target="_blank" href="' . urlShop('show_store', 'index', array('store_id' => $val['store_id'])) . '">' . $val['store_name'] . '</a>';
            $i['sc_name']                                       = (isset($val['sc_name']) && !empty($val['sc_name'])) ? $val['sc_name'] : '';
            if (in_array($val['marketing_activity_type_int'], [1,2])) {
                $i['price_contrast']                                = $val['price_contrast'];
            } else {
                $i['price_contrast']                                = $val['goods_price'].'/'.$val['kanjia_price'];
            }
            $i['apply_check']                                   = $val['apply_check'];

            $i['check_state_text']                              = (isset($val['check_state_text_fail_cause']) ? $val['check_state_text_fail_cause'] : $val['activity_state_text']) ;
            $i['check_admin_name']                              = $val['check_admin_name'];
            $data['list'][$val['marketing_activity_detail_id']] = $i;
        }
        echo Tpl::flexigridXML($data);
        exit;
    }

    /**
     * 活动内容处理
     */
    public function dealOp()
    {
        $marketing_activity_detail_ids = array();
       
        foreach (explode(',', (string)$_REQUEST['marketing_activity_detail_id']) as $i) {
            $marketing_activity_detail_ids[(int)$i] = null;
        }
        unset($marketing_activity_detail_ids[0]);
        $marketing_activity_detail_ids = array_keys($marketing_activity_detail_ids);

        if (empty($marketing_activity_detail_ids)) {
            showMessage(Language::get('activity_detail_del_choose_detail'));
        }

        //修改数据
      
        $marketing_activity    = Model('marketing_activity');
        $marketing_activity_id = isset($_REQUEST['marketing_activity_id']) ? (int)$_REQUEST['marketing_activity_id'] : 0;
       

        $update_array['check_state'] = isset($_REQUEST['check_state']) ? (int)$_REQUEST['check_state'] : 0;
        //增加添加人信息
       
        $update_array['check_time']       = TIMESTAMP;
        $update_array['check_admin_id']   = $this->admin_info['id'];
        $update_array['check_admin_name'] = $this->admin_info['name'];
        if (isset($_REQUEST['fail_cause'])) $update_array['fail_cause'] = $_REQUEST['fail_cause'];

        $alter_state = $marketing_activity->updatesGoodsData($marketing_activity_id, $marketing_activity_detail_ids, $update_array);
        if (!$alter_state) {
            $this->jsonOutput($marketing_activity->getErrorInfo());
        }

       
        $this->log(L('nc_edit,activity_index') . '[ID:' . implode(',', $marketing_activity_detail_ids) . ']', null);
        $this->jsonOutput();

    }


    /**
     * 根据活动编号删除横幅图片
     *
     * @param int $id
     */
   
    private function delActivityBanner($id)
    {
        $marketing_activity = Model('marketing_activity');
        $row                = $marketing_activity->getOneById($id);
        //删除图片文件
       
        @unlink(BASE_UPLOAD_PATH . DS . ATTACH_ACTIVITY . DS . $row['marketing_activity_banner']);
    }

    /**
     * 活动报名
     * @return html
     */
    public function activity_applyOp()
    {
        //新建处理

        if ($_POST['form_submit'] != 'ok') {
            $marketing_data = Model('marketing_activity')->getOneById($_GET['marketing_activity_id']);
            Tpl::output('marketing_data', $marketing_data);
            Tpl::showpage('marketing_activity.apply');
            exit;
        }
        //提交表单

        $obj_validate                = new Validate();
        $obj_validate->validateparam = array(
        
            array("input" => $_POST["marketing_activity_id"], "require" => "true", 'validator' => 'number', "message" => '营销活动ID为必须，且必须为数字'),
            array('input' => $_POST['goods_id'], 'validator' => 'number', "message" => '商品ID为必须，且必须为数字'),
            array('input' => $_POST['promotion_price'], 'require' => 'true', 'validator' => 'currency', 'message' => '商品特价为必须，且必须金额类型'),
            array('input' => $_POST['upper_limit'], "require" => "true", 'validator' => 'number', "message" => '购买上限为必须，且必须为数字')
        );
        
        $error                       = $obj_validate->validate();
        if ($error != '') {
            showMessage(Language::get('error') . $error, '', '', 'error');
        }

        //保存营销活动商品
        $model_marketing = $this->model_marketing;
       
        /*判断是否是拼团和砍价*/
        $marketing_data = $model_marketing->getActivityOpenDetails($_POST['marketing_activity_id']);

        /*砍价*/
        if($marketing_data['marketing_activity_type'] == 3 )
        {
            $goods_data = Model('goods')->getGoodsInfo(array('goods_id'=>$_POST['goods_id']));
            $p_kanjia_data = Model('p_kanjia')->getInfo(array('marketing_activity_id'=>$marketing_data['marketing_activity_id']));
            $goods_history = Model('goods_history')->getGoodsHistoryExtremity($_POST['goods_id']);

            $insert_data['marketing_activity_id'] = $marketing_data['marketing_activity_id'];
            $insert_data['kanjia_name'] = $marketing_data['marketing_activity_title'];
            $insert_data['kanjia_id']    = $p_kanjia_data['kanjia_id'];
            $insert_data['min_num'] = $p_kanjia_data['min_num'];
            $insert_data['store_id']    = $goods_data['store_id'];
            $insert_data['store_name']  = $goods_data['store_name'];
            $insert_data['goods_id']    = $goods_data['goods_id'];
            $insert_data['goods_name']  = $goods_data['goods_name'];
            $insert_data['goods_price'] = $goods_data['goods_price'];
            $insert_data['lowest_price'] = isset($goods_history['min_price']) ? $goods_history['min_price'] : $goods_data['goods_price'];
            $insert_data['xianshi_price'] = $_POST['promotion_price'];
            $insert_data['kanjia_price'] = $_POST['promotion_price'];
            $insert_data['gc_id'] = $goods_data['gc_id'];
            $insert_data['goods_image'] = $goods_data['goods_image'];
            $insert_data['start_time'] = $marketing_data['marketing_activity_start_date'];
            $insert_data['end_time'] = $marketing_data['marketing_activity_end_date'];
            $insert_data['upper_limit'] = 0;
            $insert_data['kanjia_state'] = 1;
            $insert_data['if_recommend'] = 0;
            $insert_data['xianshi_goods_sort'] = 0;
            $insert_data['remark'] = '';
            $insert_data['admin_apply'] = 1;
            $insert_data['apply_user_id'] = $this->admin_info['id'];
            $insert_data['apply_user_name'] = $this->admin_info['name'];
            $insert_data['create_time'] = time();
            $insert_data['update_time'] = time();
            $insert_data['check_time'] = time();
            $insert_data['check_admin_id'] = $this->admin_info['id'];
            $insert_data['check_admin_name'] = $this->admin_info['name'];
            $add_state  = Model('p_kanjia_goods')->addKanjiaGoods($insert_data);
        }
        elseif($marketing_data['marketing_activity_type'] == 4)
        {
            /*拼团*/
            $goods_data = Model('goods')->getGoodsInfo(array('goods_id'=>$_POST['goods_id']));
            $p_pintuan_data = Model('p_pintuan')->getInfo(array('marketing_activity_id'=>$marketing_data['marketing_activity_id']));
            $goods_history = Model('goods_history')->getGoodsHistoryExtremity($_POST['goods_id']);

            $insert_data['marketing_activity_id'] = $marketing_data['marketing_activity_id'];
            $insert_data['pintuan_name'] = $marketing_data['marketing_activity_title'];
            $insert_data['pintuan_id']    = $p_pintuan_data['pintuan_id'];
            $insert_data['min_num'] = $p_pintuan_data['min_num'];
            $insert_data['store_id']    = $goods_data['store_id'];
            $insert_data['store_name']  = $goods_data['store_name'];
            $insert_data['goods_id']    = $goods_data['goods_id'];
            $insert_data['goods_name']  = $goods_data['goods_name'];
            $insert_data['goods_price'] = $goods_data['goods_price'];
            $insert_data['lowest_price'] = isset($goods_history['min_price']) ? $goods_history['min_price'] : $goods_data['goods_price'];
            $insert_data['xianshi_price'] = $_POST['promotion_price'];
            $insert_data['pintuan_price'] = $_POST['promotion_price'];
            $insert_data['gc_id'] = $goods_data['gc_id'];
            $insert_data['goods_image'] = $goods_data['goods_image'];
            $insert_data['start_time'] = $marketing_data['marketing_activity_start_date'];
            $insert_data['end_time'] = $marketing_data['marketing_activity_end_date'];
            $insert_data['upper_limit'] = 0;
            $insert_data['pintuan_state'] = 1;
            $insert_data['if_recommend'] = 0;
            $insert_data['xianshi_goods_sort'] = 0;
            $insert_data['remark'] = '';
            $insert_data['admin_apply'] = 1;
            $insert_data['apply_user_id'] = $this->admin_info['id'];
            $insert_data['apply_user_name'] = $this->admin_info['name'];
            $insert_data['create_time'] = time();
            $insert_data['update_time'] = time();
            $insert_data['check_time'] = time();
            $insert_data['check_admin_id'] = $this->admin_info['id'];
            $insert_data['check_admin_name'] = $this->admin_info['name'];
            $add_state  = Model('p_pintuan_goods')->addPintuanGoods($insert_data);
        }
        else{
            //增加添加人信息
            $_POST['admin_apply']     = 1;
            $_POST['apply_user_id']   = $this->admin_info['id'];
            $_POST['apply_user_name'] = $this->admin_info['name'];
            $add_state                = $model_marketing->addMarketingActivityGoods($_POST);
        }
        if ($add_state) {
            $this->log('管理员添加了营销活动[ID:' . $_POST["marketing_activity_id"] . ']的促销商品' . '[ID:' . $_POST['goods_id'] . ']', null);
            $skip_url = (isset($_POST['if_continue']) && !empty($_POST['if_continue'])) ? "index.php?act=marketing_activity&op=activity_apply&marketing_activity_id={$_POST['marketing_activity_id']}" : "index.php?act=marketing_activity&op=detail&marketing_activity_id={$_POST['marketing_activity_id']}";
            showMessage(Language::get('nc_common_op_succ'), $skip_url);

        }
        else {
            showMessage($model_marketing->getErrorInfo());
        }
    }

    /**
     * 获取商品信息
     * @return json
     */
    public function get_goods_infoOp()
    {
       
        $result   = array('state' => false, 'msg' => '未知错误');
        $goods_id = isset($_GET['goods_id']) ? (int)$_GET['goods_id'] : 0;
        if (empty($goods_id)) {
            $result['msg'] = '请传入商品ID';
            echo json_encode($result);
            exit;
        }
        $marketing_activity_id = isset($_GET['marketing_activity_id']) ? (int)$_GET['marketing_activity_id'] : 0;
        if (empty($marketing_activity_id)) {
            $result['msg'] = '请传入活动编号';
            echo json_encode($result);
            exit;
        }
        $p_pintuan_goods = Model('p_pintuan_goods')->checkApplyAdminConflict($goods_id);
        if($p_pintuan_goods['code'] == 201){
            echo json_encode($p_pintuan_goods);
            exit;
        }
        $p_kanjia_goods = Model('p_kanjia_goods')->checkApplyAdminConflict($goods_id);
        if($p_kanjia_goods['code'] == 201){
            echo json_encode($p_kanjia_goods);
            exit;
        }
        //该商品是否参加了未过期的促销活动
        $model_p_time = Model('p_time');
       
        $map          = array(
            'end_time' => array('gt', TIMESTAMP),
            'goods_id' => array('eq', $goods_id)
        );
       
        $if_clash     = $model_p_time->getInfo($map);
        if (!empty($if_clash)) {
          
            $promotion_type      = $model_p_time->getPromotionType();
            $promotion_type_text = isset($promotion_type[$if_clash['promotion_type']]) ? $promotion_type[$if_clash['promotion_type']] : 'unknown';
          
            $result['msg']       = '该商品已经参加' . $promotion_type_text . '类型的促销活动';
            echo json_encode($result);
            exit;
        }
        //获取商品信息
        $model_goods = Model('goods');
       
        $goods_data  = $model_goods->getOnlineGoodsInfo($goods_id, 'goods_id,goods_name,store_name,goods_price,goods_promotion_price');
        if (empty($goods_data)) {
            $result['msg'] = '不存在该商品';
            echo json_encode($result);
            exit;
        }
     
        $result = array('state' => true, 'datas' => $goods_data);
        echo json_encode($result);
        exit;
    }

    /**
     * 迁移活动
     * @return json
     */
    public function migrate_activityOp()
    {
        //迁移数据
      
        $marketing_activity_detail_id  = isset($_REQUEST['marketing_activity_detail_id']) ? (string)$_REQUEST['marketing_activity_detail_id'] : '';
        $marketing_activity_detail_ids = array_filter(explode(',', $marketing_activity_detail_id));
        if (empty($marketing_activity_detail_ids)) {
            showMessage(Language::get('activity_detail_del_choose_detail'));
        }

        //处理迁移数据        
        $marketing_activity = Model('marketing_activity');
        //原营销活动id
        $marketing_activity_id = isset($_REQUEST['marketing_activity_id']) ? (int)$_REQUEST['marketing_activity_id'] : 0;
        //接收营销活动id
        $receive_activity_id = isset($_REQUEST['receive_activity_id']) ? (int)$_REQUEST['receive_activity_id'] : 0;

    
        $user_data                    = array();
        $user_data['admin_apply']     = 1;
        $user_data['apply_user_id']   = $this->admin_info['id'];
        $user_data['apply_user_name'] = $this->admin_info['name'];
     
        $alter_state                  = $marketing_activity->migrateActivityGoodsData($marketing_activity_id, $receive_activity_id, $marketing_activity_detail_ids, $user_data);
        if (!$alter_state) {
            $this->jsonOutput($marketing_activity->getErrorInfo());
        }

     
        $this->log(L('nc_edit,activity_index') . '[ID:' . implode(',', $marketing_activity_detail_ids) . ']', null);
        $this->jsonOutput();
    }

}
